package com.goldze.mvvmhabit.ui.splash;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.databinding.ObservableField;
import android.os.Handler;
import android.support.annotation.NonNull;

import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.entity.response.CompanyResponseEntity;
import com.goldze.mvvmhabit.entity.response.VersionResponseEntity;
import com.goldze.mvvmhabit.ui.login.LoginActivity;
import com.goldze.mvvmhabit.utils.RetrofitClient;
import com.goldze.mvvmhabit.utils.UserManager;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;

public class SplashViewModel extends BaseViewModel<DemoRepository> {

    public ObservableField<String> timeChange = new ObservableField<>("");

    public SingleLiveEvent<String> spalshChangeBg = new SingleLiveEvent<>();

    public SingleLiveEvent<String> showDialogUpdataAPP = new SingleLiveEvent<>();

    public boolean isGetVersion = false;
    private boolean isEndTimed = false;


    public SplashViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    //登录按钮的点击事件
    public BindingCommand jumpMainOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (mDisposable != null) {
                mDisposable.dispose();
            }
            startActivity(LoginActivity.class);
//            startContainerActivity(ViewPagerGroupFragment.class.getCanonicalName());
            finish();
        }
    });

    private int index = 3;
    private Disposable mDisposable = null;

    public void timedTransmission() {
        timeChange.set("跳过 " + index);
        Observable.interval(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        index--;
                        timeChange.set("跳过 " + index);
                        if (index == 1) {
                            isEndTimed = true;
                            mDisposable.dispose();
                            jumpIntent();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public void getCompany() {
        model.getCompany()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<CompanyResponseEntity>>() {
                    @Override
                    public void accept(BaseResponse<CompanyResponseEntity> response) throws Exception {
                        if (response.isSuccess() && response != null && response.getResponse() != null) {
                            spalshChangeBg.setValue(RetrofitClient.baseUrl + response.getResponse().getLogo());
                            UserManager.getAppManager().setmCompany(response.getResponse());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        KLog.d("获取公司信息");
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                    }
                });
    }

    public void getCheckVersion() {
        model.getCheckVersion()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<VersionResponseEntity>>() {
                    @Override
                    public void accept(BaseResponse<VersionResponseEntity> response) throws Exception {
                        if (response.isSuccess() && response != null && response.getResponse() != null) {
                            if (response.getResponse().getVersion().equals(String.valueOf(packageCode(getApplication())))) {
                                isGetVersion = true;
                                jumpIntent();
                            } else {
                                showDialogUpdataAPP.setValue(response.getResponse().getUrl());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        KLog.d("获取最新版本信息");
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                    }
                });
    }

    private boolean isRun = false;

    public void jumpIntent() {
        if (isEndTimed && isGetVersion && !isRun) {
            isRun = true;
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    startActivity(LoginActivity.class);
//                    startContainerActivity(ViewPagerGroupFragment.class.getCanonicalName());
                    finish();
                }
            }, 500);   //5秒
        }
    }

    public int packageCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

}
